package cn.fl.customer.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.fl.customer.service.ICstCorpBscInfoService;
import cn.fl.customer.service.ICstCorpShrService;
import cn.fl.customer.transform.CstCorpShrVOTransform;
import cn.fl.customer.vo.CstCorpBscInfoVO;
import cn.fl.customer.vo.CstCorpShrVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysDictionaryService;
import fl.customer.facade.customer.condition.CstCorpShrQueryCondition;
import fl.customer.facade.customer.constant.CustomerConstant;
import fl.customer.facade.customer.dto.CstCorpShrDTO;

/**
 * @Description: 法人股东信息表 控制层
 */
@Controller
@RequestMapping("/customer/cstcorpshr")
public class CstCorpShrController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CstCorpShrController.class);

	/**
	 * CstCorpShr 服务层BEAN
	 */
	@Autowired
	private ICstCorpShrService cstCorpShrService;

	/**
	 * CstCorpBscInfo 服务层BEAN
	 */
	@Autowired
	private ICstCorpBscInfoService cstCorpBscInfoService;
	
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryService sysDictionaryService;
	
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		logger.info("加载CstCorpShr列表页面.");
		ModelAndView view = new ModelAndView("customer/cstCorpShr/list");
		return view;
	}
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String ccsId = request.getParameter("ccsId");
		ModelAndView view = new ModelAndView("customer/cstcorpshr/cstCorpShrDetail");
		view.addObject("ccsId", ccsId);
		return view;
	}

	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String cstId = request.getParameter("cstId");
		String ccsId = request.getParameter("ccsId");
		ModelAndView view = new ModelAndView("customer/cstcorpshr/cstCorpShrAdd");
		view.addObject("cstId", cstId);
		view.addObject("ccsId", ccsId);//修改时使用的关联关系ID
		
		Map<String, List<KeyValueVO>> dicMap = null;
		try {
			List<String> codeGrpCdList = new ArrayList<>();
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_CST_SHR_TYP_CD);
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_CERT_TYP_CD);
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_CST_SHR_CONTR_WAY_CD);
			dicMap = this.sysDictionaryService.getMultiKvList(CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd(), codeGrpCdList);
		} catch (Exception e) {
			BaseLogUtils.info(logger, "toAddPage", "获取数据字典失败!"+e.getMessage());
		}finally {
			if(CollectionUtils.isMapEmpty(dicMap)){
				dicMap = new HashMap<String, List<KeyValueVO>>();
			}
		}
		
		view.addObject("searchSelectShrTypCdList", dicMap.get(DictionaryConstant.CODE_GRP_CST_SHR_TYP_CD));// 婚姻状况
		view.addObject("searchSelectCertTypCdList", dicMap.get(DictionaryConstant.CODE_GRP_CERT_TYP_CD));// 性别状况
		view.addObject("searchSelectContrWayList", dicMap.get(DictionaryConstant.CODE_GRP_CST_SHR_CONTR_WAY_CD));//职业
		return view;
	}
	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String cstId = request.getParameter("cstId");
		String isEncrypt=request.getParameter("isEncrypt");

		if(StringUtils.isEmpty(cstId)){
			ListPageVO<CstCorpShrVO> listPage = new ListPageVO<CstCorpShrVO>(new ArrayList<CstCorpShrVO>(), 0);
			return listPage;
		}
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		CstCorpShrQueryCondition qc = new CstCorpShrQueryCondition();
		List<Long> cstIdList = new ArrayList<>();
		cstIdList.add(Long.valueOf(cstId));
		qc.setCstIdList(cstIdList);
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		page.setCondition(qc);
		//page.setEveryPage(Integer.MAX_VALUE);//最大数据量
		logger.info("==初始化列表数据.==");
		Pager pager =this.cstCorpShrService.searchListPage(page);
		String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();

		List<CstCorpShrDTO> list = (List<CstCorpShrDTO>) pager.getResultList();
		if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)) {
			for (CstCorpShrDTO dto:list ) {
				dto.setCertNo(EncryptUtil.certNoEncrypt(dto.getCertNo()));
			}
		}
		List<CstCorpShrVO> voList = CstCorpShrVOTransform.toVOList(list);
		ListPageVO<CstCorpShrVO> listPage = new ListPageVO<CstCorpShrVO>(voList, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		try {
			List<Long> idList = new ArrayList<>();
			idList.add(Long.valueOf(id));
			this.cstCorpShrService.removeByIds(idList);
			logger.debug("==remove==id:" + id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("删除失败");
			logger.error("删除失败!", ex);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String isEncrypt=request.getParameter("isEncrypt");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("参数不完整！");
			return result;
		}
		
		try {
			CstCorpShrVO vo = this.cstCorpShrService.selectById(Long.valueOf(id));
			String roleIsEncrypt=this.sysDictionaryService.getRoleisEncrypt();

			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在！");
			}else{
				Date contrDt = vo.getContrDt();
				if(contrDt!=null){
					DateUtils.formatDate(contrDt, DateUtils.YYYY_MM_DD);
					vo.setContrDt(contrDt);
				}
				if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(roleIsEncrypt)) {
					vo.setCertNo(EncryptUtil.certNoEncrypt(vo.getCertNo()));
				}
			}
			result.setData(vo);
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.error(ex.getMessage(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取数据失败！");
			logger.error("获取数据失败！", ex);
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		try {
			CstCorpShrVO entity = this.getRequestParams(request);
			entity.setIsDel(BaseConstant.IS_YESNO_NO);
			entity.setCrtTm(new Date());
			entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			Long id = this.cstCorpShrService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			logger.info(ex.getMessage(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("新增失败!");
			logger.error("", ex);
		}

		return result;
	}
	/**
	 * 计算出资占比
	 */
	@RequestMapping(value = "/countEquPropPct.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object countEquPropPct(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String cntrAmtStr = request.getParameter("cntrAmt");//出资金额
		String cstId = request.getParameter("cstId");//客户id
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isBlank(cstId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("客户主键不能为空!");
			return result;
		}
		
		if(StringUtils.isBlank(cntrAmtStr)){
			result.setData("0");
			return result;
		}
		
		if(!StringUtils.isUnsignedNumeric(cntrAmtStr)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("请输入正确的金额!");
			return result;
		}
		Double res = 0D;//最终运算的结果
		try {
			CstCorpBscInfoVO cstCorpBscInfoVO = cstCorpBscInfoService.selectById(Long.valueOf(cstId));
			Double regCapAmt = cstCorpBscInfoVO.getRegCapAmt();//注册资金
			String regCapUntCd = cstCorpBscInfoVO.getRegCapUntCd();// 注册资金单位
			Double cntrAmt = Double.valueOf(cntrAmtStr);
			cntrAmt = DecimalUtils.mul(cntrAmt, 10000);//乘以单位万元
			//首先要检查输入的金额是否大于注册资本金
			if(regCapUntCd.equals(CustomerConstant.CST_REG_CAP_UNT_DOLLAR_CD)){//美元
				Double sum = DecimalUtils.mul(regCapAmt, CustomerConstant.CST_RMD_DOLLAR_RATE);//美元转元
				if(DecimalUtils.compareTo(cntrAmt, sum) > 0){//如果输入的金额大于了注册资本金则提示
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "输入金额不能大于注册资本金!");
				}
				res= DecimalUtils.mul(DecimalUtils.div(cntrAmt, sum, CustomerConstant.CST_DIV_RES_DEC_BIT), CustomerConstant.CST_DEC_TRAN_PER_BASE);
			}
			if(regCapUntCd.equals(CustomerConstant.CST_REG_CAP_UNT_RMB_CD)){//人民币
				Double sum = DecimalUtils.mul(regCapAmt, 10000);//万元转元
				if(DecimalUtils.compareTo(cntrAmt, sum) > 0){//如果输入的金额大于了注册资本金则提示
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, "输入金额不能大于注册资本金!");
				}
				res= DecimalUtils.mul(DecimalUtils.div(cntrAmt, sum, CustomerConstant.CST_DIV_RES_DEC_BIT), CustomerConstant.CST_DEC_TRAN_PER_BASE);
			}
			result.setData(res);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}
		
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("ccsId");
		CstCorpShrVO entity = this.getRequestParams(request);
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			entity.setId(Long.valueOf(id));
			entity.setMdfTm(new Date());
			entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			boolean success = this.cstCorpShrService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		}
		return result;
	}
	
	
	//***************************************私有方法********************//
	/**
	 * 获取新增修改参数
	 */
	private CstCorpShrVO getRequestParams(HttpServletRequest request) {
		String cstId = request.getParameter("cstId");//客户id
		String shrTypCd = request.getParameter("shrTypCd");//股东类型
		String shrNm = request.getParameter("shrNm");//股东名称
		String certTypCd = request.getParameter("certTypCd");//证件类型
		String certNo = request.getParameter("certNo");//证件号
		String cntrAmt = request.getParameter("cntrAmt");//出资情况
		String contrWay = request.getParameter("contrWay");//出资方式
		String contrDt = request.getParameter("contrDt");//出资日期
		String equPropPct = request.getParameter("equPropPct");//出资占比
		String shrRemark = request.getParameter("shrRemark");//备注
		
		if(StringUtils.isEmpty(cstId) || !StringUtils.isNumeric(cstId)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请确保客户信息存在后在进行操作!");
		}
		
		if(StringUtils.isNotEmpty(certTypCd) && certTypCd.equals(DictionaryConstant.CODE_CERT_TYP_CD_0) && StringUtils.isNotEmpty(certNo)&& !StringUtils.isIdCardNumber(certNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请输入正确的身份证号码");
		}
		
		if(StringUtils.isEmpty(shrNm)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "股东名称不能为空!");
		}
		
		
		CstCorpShrVO entity = new CstCorpShrVO();
		entity.setCertNo(certNo);
		entity.setCertTypCd(certTypCd);
		if(StringUtils.isNotBlank(cntrAmt)){
			
			entity.setCntrAmt(Double.valueOf(cntrAmt));
		}
		entity.setContrWay(contrWay);
		entity.setCstId(Long.valueOf(cstId));
		if(StringUtils.isNotBlank(cntrAmt)){
			
			entity.setEquPropPct(Double.valueOf(equPropPct));
		}
		
		entity.setShrNm(shrNm);
		entity.setShrRemark(shrRemark);
		entity.setShrTypCd(shrTypCd);
		if(StringUtils.isNotBlank(contrDt)){
			entity.setContrDt(DateUtils.formatStringToDate(contrDt, DateUtils.YYYY_MM_DD));
		}else{
			entity.setContrDt(null);
		}
		
		return entity;
	}
}

